package cn.niter.forum.controller;

import cn.niter.forum.dto.*;
import cn.niter.forum.enums.CommentTypeEnum;
import cn.niter.forum.exception.CustomizeErrorCode;
import cn.niter.forum.exception.CustomizeException;
import cn.niter.forum.model.Comment;
import cn.niter.forum.model.Question;
import cn.niter.forum.model.UserAccount;
import cn.niter.forum.provider.BaiduCloudProvider;
import cn.niter.forum.service.CommentService;
import cn.niter.forum.service.QuestionService;
import com.tencentcloudapi.vod.v20180717.models.ComposeMediaRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * @author wadao
 * @version 2.0
 * @date 2020/5/1 15:17
 * @site niter.cn
 */

@Controller
public class CommentController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private BaiduCloudProvider baiduCloudProvider;

    @ResponseBody//@ResponseBody返回json格式的数据
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO,//@RequestBody接受json格式的数据
                       HttpServletRequest request) {

        UserDTO user = (UserDTO) request.getAttribute("loginUser");
        if (user == null) {
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }

        if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())) {
            return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }
        ResultDTO resultDTO = baiduCloudProvider.getTextCensorReult(commentCreateDTO.getContent());
        if(resultDTO.getCode()!=1){
            return resultDTO;
        }

        Comment comment = new Comment();
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setContent(commentCreateDTO.getContent());
        comment.setType(commentCreateDTO.getType());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setCommentator(user.getId());
        comment.setLikeCount(0L);
        UserAccount userAccount = new UserAccount();
        userAccount.setVipRank(user.getVipRank());
        userAccount.setGroupId(user.getGroupId());
        userAccount.setUserId(user.getId());
        commentService.insert(comment,user,userAccount);

       return ResultDTO.okOf("回复成功！");

    }


    @ResponseBody
    @RequestMapping(value = "/comment/{id}", method = RequestMethod.GET)
    public ResultDTO<List<CommentDTO>> comments(@PathVariable(name = "id") Long id) {
        List<CommentDTO> commentDTOS = commentService.listByTargetId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentDTOS);
    }

    @ResponseBody
    @RequestMapping(value = "/api/comment/list", method = RequestMethod.POST)
    public ResultDTO<List<CommentDTO>> commentList(
            /*@RequestParam(name = "commentator",required = false) Long commentator
            ,@RequestParam(name = "type",required = false) Integer type
            ,@RequestParam(name = "id",required = false) Long id
            ,@RequestParam(name = "parentId",required = false) Long parentId*/
            @RequestBody CommentQueryDTO commentQueryDTO
            ) {
        PaginationDTO paginationDTO = commentService.listByCommentQueryDTO(commentQueryDTO);


        return ResultDTO.okOf(paginationDTO);
    }

    @PostMapping("/comment/del/id")
    @ResponseBody
    public Map<String,Object> deleteCommentById(HttpServletRequest request,
                                                     @RequestParam(name = "id",defaultValue = "0") Long id
                                                     ,@RequestParam(name = "type",defaultValue = "0") Integer type ) {

        UserDTO user = (UserDTO) request.getAttribute("loginUser");
        UserAccount userAccount = new UserAccount();
        userAccount.setVipRank(user.getVipRank());
        userAccount.setGroupId(user.getGroupId());
        userAccount.setUserId(user.getId());
        if (user == null||userAccount==null) {
            throw new CustomizeException(CustomizeErrorCode.NO_LOGIN);
        }
        Map<String,Object> map  = new HashMap<>();
        if(id==null||id==0||type==null||type==0) {
            map.put("code",500);
            map.put("msg","妈呀，出问题啦！");
        }
        else {
            int c = commentService.delCommentByIdAndType(user.getId(),userAccount.getGroupId(),id,type);
            if(c==0) {
                map.put("code",500);
                map.put("msg","哎呀，该评论已删除或您无权删除！");
            }
            else {
                map.put("code",200);
                map.put("msg","恭喜您，成功删除"+c+"条评论及子评论！");
            }
        }
        return map;
    }

    @PostMapping("/api/jieda-accept")
    @ResponseBody
    public Map<String,Object> jiedaAccept(HttpServletRequest request,
                                          @RequestParam(name = "id",defaultValue = "0") Long id){
        Map<String,Object> map  = new HashMap<>();
        UserDTO user = (UserDTO) request.getAttribute("loginUser");
        UserAccount userAccount = new UserAccount();
        userAccount.setVipRank(user.getVipRank());
        userAccount.setGroupId(user.getGroupId());
        userAccount.setUserId(user.getId());
        if (user == null||userAccount==null) {
            throw new CustomizeException(CustomizeErrorCode.NO_LOGIN);
        }
        String referer = request.getHeader("referer");
        referer = referer.replaceAll(".*[^\\d](?=(\\d+))","");
        if(referer == null||referer == ""){
            map.put("code",500);
            map.put("msg","哎呀，请从原帖子页面点击采纳");
            return map;
        }
        Comment jiedaComment = commentService.getCommentById(id);
        if(jiedaComment==null){
            map.put("code",500);
            map.put("msg","糟了，这个回复不见了");
            return map;
        }
        if(jiedaComment.getType()!=1){
            map.put("code",500);
            map.put("msg","哎呀，被采纳的答案不能是楼中楼的回复");
            return map;
        }

        Long question_id = Long.valueOf(referer) ;
        Question question = questionService.getQuestionById(question_id);
        if(question==null){
            map.put("code",500);
            map.put("msg","糟了，这个帖子不见了");
            return map;
        }
        if(question.getIssolved()!=0L){
            map.put("code",500);
            map.put("msg","哎呀，帖子已经有答案被采纳过了");
            return map;
        }else if(question.getCreator()!=userAccount.getUserId()){
            map.put("code",500);
            map.put("msg","哎呀，只有帖子主人才能采纳");
            return map;
        }else if(jiedaComment.getParentId()!=question_id){
            map.put("code",500);
            map.put("msg","哎呀，这个被采纳的回复好像不属于这个帖子");
            return map;
        }
        questionService.updateQuestionIsSolved(question_id,id);
        map.put("code",200);
        map.put("msg","你已经成功采纳这个回复啦！");
        return map;
    }


}
